/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.boot.mongo.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.iwindplus.boot.domain.DocDbBaseDO;
import com.iwindplus.boot.domain.constant.CommonConstant;
import com.iwindplus.boot.domain.context.UserContextHolder;
import com.iwindplus.boot.domain.vo.UserBaseVO;
import com.iwindplus.boot.mongo.domain.property.MongoProperty;
import com.iwindplus.boot.mongo.service.MongoBaseService;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import jakarta.annotation.Resource;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.util.Pair;
import org.springframework.util.ReflectionUtils;

/**
 * mongo业务层基础接口实现类.
 *
 * @param <T> 对象
 * @author zengdegui
 * @since 2019/8/9
 */
@Slf4j
@Getter
public class MongoBaseServiceImpl<T extends DocDbBaseDO> implements MongoBaseService<T> {

    /**
     * 反射实体.
     */
    private final Class<T> entityClass;

    /**
     * MongoTemplate.
     */
    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private MongoProperty property;

    /**
     * 构造方法.
     */
    public MongoBaseServiceImpl() {
        this.entityClass = (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), MongoBaseServiceImpl.class, 0);
    }

    @Override
    public T save(T entity) {
        this.buildDefaultEntity(entity);
        return this.mongoTemplate.save(entity);
    }

    @Override
    public Collection<T> saveBatch(Collection<T> entities, int batchSize) {
        if (CollUtil.isEmpty(entities)) {
            return null;
        }
        entities.forEach(this::buildDefaultEntity);
        if (entities.size() <= batchSize) {
            return this.mongoTemplate.insertAll(entities);
        }
        Collection<T> resultList = new ArrayList<>(10);
        List<List<T>> splitList = CollUtil.split(entities, batchSize);
        splitList.forEach(subItems -> resultList.addAll(this.mongoTemplate.insertAll(subItems)));
        return resultList;
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<T> entities, int batchSize) {
        if (CollUtil.isEmpty(entities)) {
            return false;
        }
        boolean saveResult = false;
        boolean editResult = false;
        List<T> saveList = entities.stream().filter(m -> CharSequenceUtil.isBlank(m.getId())).toList();
        if (CollUtil.isNotEmpty(saveList)) {
            saveResult = CollUtil.isNotEmpty(this.saveBatch(saveList, batchSize));
        }
        List<T> editList = entities.stream().filter(m -> CharSequenceUtil.isNotBlank(m.getId())).toList();
        if (CollUtil.isNotEmpty(editList)) {
            editResult = this.updateBatchById(editList, batchSize);
        }
        return saveResult || editResult;
    }

    @Override
    public boolean removeByIds(Collection<?> ids, boolean deleted) {
        if (CollUtil.isEmpty(ids)) {
            return false;
        }
        final Query query = Query.query(Criteria.where(CommonConstant.DbConstant.ID).in(ids));
        return this.remove(query, deleted);
    }

    @Override
    public boolean remove(Query query, boolean deleted) {
        // 真实删除
        if (Boolean.TRUE.equals(deleted)) {
            DeleteResult result = this.mongoTemplate.remove(query, this.entityClass);
            return Optional.ofNullable(result).map(p -> p.getDeletedCount() > 0).orElse(Boolean.FALSE);
        }
        // 假删除
        query.addCriteria(this.getCriteriaDeleted());
        final Update update = this.getUpdateDeleted();
        final UpdateResult result = this.mongoTemplate.updateMulti(query, update, this.entityClass);
        return Optional.ofNullable(result).map(p -> p.getModifiedCount() > 0).orElse(Boolean.FALSE);
    }

    @Override
    public boolean updateById(T entity) {
        if (Objects.isNull(entity)) {
            return false;
        }
        final Query query = Query.query(Criteria.where(CommonConstant.DbConstant.ID).is(entity.getId()));
        return this.update(entity, query);
    }

    @Override
    public boolean update(T entity, Query query) {
        query.addCriteria(this.getCriteriaDeleted());
        Update update = this.getUpdate(entity);
        UpdateResult result = this.mongoTemplate.updateMulti(query, update, this.entityClass);
        return Optional.ofNullable(result).map(p -> p.getModifiedCount() > 0).orElse(Boolean.FALSE);
    }

    @Override
    public boolean updateBatchById(Collection<T> entities, int batchSize) {
        if (CollUtil.isEmpty(entities)) {
            return false;
        }
        if (entities.size() <= batchSize) {
            return this.updateBatchByIds(entities);
        }
        List<Boolean> resultList = new ArrayList<>(10);
        List<List<T>> splitList = CollUtil.split(entities, batchSize);
        splitList.forEach(subItems -> resultList.add(this.updateBatchByIds(subItems)));
        if (CollUtil.isNotEmpty(resultList)) {
            return resultList.stream().allMatch(Boolean.TRUE::equals);
        }
        return false;
    }

    @Override
    public <E extends IPage<T>> E page(E page, Query query) {
        // 排序
        List<Sort.Order> orders = new ArrayList<>(10);
        List<OrderItem> orderList = page.orders();
        if (CollUtil.isEmpty(orderList)) {
            orders.add(Sort.Order.desc(CommonConstant.DbConstant.MODIFIED_TIME));
        } else {
            orderList.forEach(order -> {
                Sort.Order item;
                if (order.isAsc()) {
                    item = Sort.Order.asc(order.getColumn());
                } else {
                    item = Sort.Order.desc(order.getColumn());
                }
                orders.add(item);
            });
        }
        query.addCriteria(this.getCriteriaDeleted());
        long count = this.mongoTemplate.count(query, this.entityClass);
        if (count > 0) {
            PageRequest pageRequest = PageRequest.of((int) page.getCurrent() - 1, (int) page.getSize());
            List<T> list = this.mongoTemplate.find(query.with(pageRequest).with(Sort.by(orders)), this.entityClass);
            page.setRecords(list);
            page.setTotal(count);
        }
        return page;
    }

    @Override
    public List<T> list() {
        Query query = Query.query(this.getCriteriaDeleted());
        return this.mongoTemplate.find(query, this.entityClass);
    }

    @Override
    public List<T> list(Query query) {
        query.addCriteria(this.getCriteriaDeleted());
        return this.mongoTemplate.find(query, this.entityClass);
    }

    @Override
    public T getById(String id) {
        if (CharSequenceUtil.isBlank(id)) {
            return null;
        }
        return this.mongoTemplate.findById(id, this.entityClass);
    }

    @Override
    public T getOne(Query query) {
        query.addCriteria(this.getCriteriaDeleted());
        return this.mongoTemplate.findOne(query, this.entityClass);
    }

    @Override
    public long count(Query query) {
        query.addCriteria(this.getCriteriaDeleted());
        return this.mongoTemplate.count(query, this.entityClass);
    }

    private boolean updateBatchByIds(Collection<T> entities) {
        List<Pair<Query, UpdateDefinition>> updateList = new ArrayList<>(10);
        entities.forEach(entity -> {
            Query query = this.getQuery(entity);
            Update update = this.getUpdate(entity);
            updateList.add(Pair.of(query, update));
        });
        BulkOperations operations = this.mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, this.entityClass);
        BulkWriteResult result = operations.updateMulti(updateList).execute();
        return Optional.ofNullable(result).map(p -> p.getModifiedCount() > 0).orElse(Boolean.FALSE);
    }

    private void buildDefaultEntity(T entity) {
        LocalDateTime now = LocalDateTime.now();
        int numberZero = CommonConstant.NumberConstant.NUMBER_ZERO;
        final UserBaseVO userInfo = this.getCurrentUserInfo();
        Long userId = userInfo.getUserId();
        String realName = userInfo.getRealName();
        // 设置id
        entity.setId(null);
        if (Boolean.TRUE.equals(this.property.getField().getFill().getEnabled())
            && Boolean.TRUE.equals(this.property.getField().getFill().getInsertStrict())) {
            this.buildFinalAttrByInsert(entity, now, userId, realName);
        } else {
            this.buildOptionalByInsert(entity, now, userId, realName);
        }
        // 设置是否删除.
        entity.setDeleted(numberZero);
        // 设置乐观锁.
        entity.setVersion(numberZero);
    }

    private void buildFinalAttrByInsert(T entity, LocalDateTime now, Long userId, String realName) {
        // 设置创建时间.
        entity.setCreatedTime(now);
        // 设置创建人.
        entity.setCreatedBy(realName);
        // 设置创建人主键.
        entity.setCreatedId(userId);
        // 设置更新时间.
        entity.setModifiedTime(now);
        // 设置更新人.
        entity.setModifiedBy(realName);
        // 设置更新人主键.
        entity.setModifiedId(userId);
    }

    private void buildOptionalByInsert(T entity, LocalDateTime now, Long userId, String realName) {
        // 设置创建时间.
        if (Objects.isNull(entity.getCreatedTime())) {
            entity.setCreatedTime(now);
        }
        // 设置创建人.
        if (CharSequenceUtil.isBlank(entity.getCreatedBy())) {
            entity.setCreatedBy(realName);
        }
        // 设置创建人主键.
        if (Objects.isNull(entity.getCreatedId())) {
            entity.setCreatedId(userId);
        }
        // 设置更新时间.
        if (Objects.isNull(entity.getModifiedTime())) {
            entity.setModifiedTime(now);
        }
        // 设置更新人.
        if (CharSequenceUtil.isBlank(entity.getModifiedBy())) {
            entity.setModifiedBy(realName);
        }
        // 设置更新人主键.
        if (Objects.isNull(entity.getModifiedId())) {
            entity.setModifiedId(userId);
        }
    }

    private Query getQuery(T entity) {
        final Criteria criteria = Criteria.where(CommonConstant.DbConstant.ID).is(entity.getId()).andOperator(this.getCriteriaDeleted());
        if (Objects.nonNull(entity.getVersion())) {
            criteria.and(CommonConstant.DbConstant.VERSION).is(entity.getVersion());
        }
        return Query.query(criteria);
    }

    private Update getUpdateDeleted() {
        final UserBaseVO userInfo = this.getCurrentUserInfo();
        return Update.update(CommonConstant.DbConstant.DELETED, CommonConstant.NumberConstant.NUMBER_ONE)
            .set(CommonConstant.DbConstant.MODIFIED_TIME, LocalDateTime.now())
            .set(CommonConstant.DbConstant.MODIFIED_BY, userInfo.getRealName())
            .set(CommonConstant.DbConstant.MODIFIED_ID, userInfo.getUserId());
    }

    private Update getUpdate(T entity) {
        Update update = this.buildFinalAttrByUpdate(entity);
        if (Objects.nonNull(entity.getVersion())) {
            update.set(CommonConstant.DbConstant.VERSION, entity.getVersion() + 1);
        }
        return update;
    }

    private Update buildFinalAttrByUpdate(T entity) {
        final UserBaseVO userInfo = this.getCurrentUserInfo();
        Update update = new Update();
        Map<String, Object> tableField = this.getTableField(entity);
        tableField.put(CommonConstant.DbConstant.MODIFIED_TIME, LocalDateTime.now());
        tableField.put(CommonConstant.DbConstant.MODIFIED_BY, userInfo.getRealName());
        tableField.put(CommonConstant.DbConstant.MODIFIED_ID, userInfo.getUserId());
        tableField.entrySet().stream().forEach(field -> update.set(field.getKey(), field.getValue()));
        return update;
    }

    private Map<String, Object> getTableField(T entity) {
        Map<String, Object> resultMap = new HashMap<>(16);
        Field[] fields = entity.getClass().getDeclaredFields();
        if (ArrayUtil.isNotEmpty(fields)) {
            for (Field field : fields) {
                ReflectionUtils.makeAccessible(field);
                String fieldName = field.getName();
                if (CommonConstant.DbConstant.ID.equals(fieldName)) {
                    continue;
                }
                Object fieldValue = ReflectUtil.getFieldValue(entity, field);
                if (Objects.nonNull(fieldValue)) {
                    resultMap.put(fieldName, fieldValue);
                }
            }
        }
        return resultMap;
    }

    private Criteria getCriteriaDeleted() {
        return Criteria.where(CommonConstant.DbConstant.DELETED).is(CommonConstant.NumberConstant.NUMBER_ZERO);
    }

    private UserBaseVO getCurrentUserInfo() {
        return Optional.ofNullable(UserContextHolder.getContext()).orElse(UserContextHolder.getDefaultUser());
    }
}
